<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>滤镜函数实现美颜-灰度化图片</title>
    <style>
        canvas{
            border:1px solid #ccc;
        }
    </style>
</head>
<body>
    <canvas width="0" height="0"></canvas>

    <script type="module">
        const canvas = document.querySelector("canvas");
        const ctx = canvas.getContext("2d");

        // 加载图片的函数
        async function loadImg(src){
            const img = new Image();
            img.crossOrigin = "anonymous";
            return new Promise((resolve)=>{
                img.onload = function(){
                    resolve(img);
                }
                img.src = src;
            });
        }
        // 处理图片像素
        function handleImageData(imageData){
            const { width, height, data } = imageData;
            // data.length = width * height * 4
            for (let i = 0; i < data.length; i += 4) {
                const r = data[i],
                    g = data[i + 1],
                    b = data[i + 2],
                    a = data[i + 3];

                const q = 0.2126 * r + 0.7152 * g + 0.0722 * b;
                data[i] = q;
                data[i + 1] = q;
                data[i + 2] = q;
                data[i + 3] = a;
            }
            return imageData;
        }
        
        // 渲染
        (async function(){
            const img = await loadImg("./assets/girl1.jpg");
            const { width, height } = img;
            canvas.width = width;
            canvas.height = height;

            ctx.drawImage(img, 0, 0);

            // 获取像素点
            const imageData = ctx.getImageData(0, 0, width, height);
            // 处理像素点
            const result = handleImageData(imageData);
            ctx.putImageData(result, 0, 0);
        })();

    </script>
</body>
</html>